//
//  YDAMineController.m
//  siyanone
//
//  Created by LK-IOS on 2018/3/21.
//  Copyright © 2018年 LK-News. All rights reserved.
//

#import "YDAMineController.h"
#import "YDAMineLoginTopView.h"
#import "YDAMineUnLoginTopView.h"
#import "YDAMineTableCell.h"
#import <AFNetworking.h>
#import <SDWebImage/SDImageCache.h>

#import "YDALoginController.h"
#import "YDARegisterController.h"
#import "YDAAboutUsController.h"
#import "YDAAccountSettingController.h"


@interface YDAMineController ()<UITableViewDelegate , UITableViewDataSource , SYAMineLoginTopViewDelegate , SYAMineUnLoginTopViewDelegate>

//tableView
@property (nonatomic , weak) UITableView *tableView;
//YDAMineUnLoginTopView
@property (nonatomic , weak) YDAMineUnLoginTopView *unLoginView;
//YDAMineLoginTopView
@property (nonatomic , weak) YDAMineLoginTopView *topView;

@end

@implementation YDAMineController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor colorWithHexString:mainGray];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [self tableView];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([SYUserInformation sharedInstance].isLogin) {
        [self topView];
        [self refreshUserInfo];
    }else{
        [self unLoginView];
    }
    
    [self.tableView reloadData];
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (![SYUserInformation sharedInstance].isLogin) {
        [self unLoginView];
        [self.tableView reloadData];
    }
}

-(void)refreshUserInfo
{
    [BaseNetRequest sessionRequestWithparameters:nil method:GETMethod requstType:GetUerInfo WithSuccessBlock:^(NSDictionary *resultDict) {
        if ([resultDict[@"code"] integerValue] == 200) {
            //成功刷新用户信息
            if (((NSDictionary *)resultDict[@"result"]).count) {
                
                [[SYUserDataManger sharedInstance] storeUserDataWithDict:resultDict[@"result"]];
                
                self.topView.dict = resultDict[@"result"];
                
            }
            
        }
    } failBlock:^(NSError *error) {
        //失败不做处理
        
    }];
}

-(YDAMineUnLoginTopView *)unLoginView
{
    if (_unLoginView == nil) {
        CGRect topViewFrame;
        if (isPhoneX) {
            topViewFrame = CGRectMake(0, 0, LKScreenW, rateX812(210));
        }else{
            topViewFrame = CGRectMake(0, 0, LKScreenW, rate750(210));
        }
        YDAMineUnLoginTopView *unLoginView = [[YDAMineUnLoginTopView alloc] init];
        unLoginView.frame = topViewFrame;
        unLoginView.delegate = self;
        self.tableView.tableHeaderView = unLoginView;
    }
    return _unLoginView;
}
/*******SYAMineUnLoginTopViewDelegate***********/
-(void)aMineUnLoginTopView:(YDAMineUnLoginTopView *)unTopView clickStyle:(SYAMineUnLoginTopViewClickStyle)style
{
    if (style == SYAMineUnLoginTopViewIcon) {
        
    }else if (style == SYAMineUnLoginTopViewClickLogin){//去登陆
      
        YDALoginController *vc = [[YDALoginController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
        
    }else if (style == SYAMineUnLoginTopViewClickRegister){//去注册
        
        YDARegisterController *vc = [[YDARegisterController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }
}


/******YDAMineLoginTopView*******/
-(YDAMineLoginTopView *)topView
{
    if (_topView == nil) {
        CGRect topViewFrame;
        if (isPhoneX) {
            topViewFrame = CGRectMake(0, 0, LKScreenW, rateX812(210));
        }else{
            topViewFrame = CGRectMake(0, 0, LKScreenW, rate750(210));
        }
        YDAMineLoginTopView *topView = [YDAMineLoginTopView mineLoginTopViewInitWithFrame:topViewFrame andDict:[[SYUserDataManger sharedInstance] getUserDict]];
        topView.frame = topViewFrame;
        topView.delegate = self;
        self.tableView.tableHeaderView = topView;
    }
    return _topView;
}
/**********SYAMineLoginTopViewDelegate**************/
-(void)aMineLoginTopView:(YDAMineLoginTopView *)topView clickStyle:(SYAMineLoginTopViewClickStyle)style
{
    //去账户设置
    YDAAccountSettingController *vc = [[YDAAccountSettingController alloc] init];
    vc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:vc animated:YES];
    
}

/*******tableView********/
-(UITableView *)tableView
{
    if (_tableView == nil) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, LKScreenW, self.view.height - self.tabBarController.tabBar.height) style:UITableViewStylePlain];
        [self.view addSubview:tableView];
        tableView.backgroundColor = NumberColor(247, 247, 247);
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.scrollEnabled = NO;
        if (isIos11) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _tableView = tableView;
    }
    return _tableView;
}

#pragma UITableViewDelegate , UITableViewDataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else if (section == 1){
        return 1;
    }else{
        if ([SYUserInformation sharedInstance].isLogin) {
            return 2;
        }else{
            return 1;
        }
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return isPhoneX ? rateX812(10) : rate750(10);
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return isPhoneX ? rateX812(50) : rate750(50);;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0f;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    YDAMineTableCell *cell = [YDAMineTableCell cellWithTableView:tableView];
    if (indexPath.section == 0) {
        cell.imageName = @"mjbtwoaccount";
        cell.cellName = @"账户设置";
    }else if (indexPath.section == 1){
        cell.imageName = @"mjbtwo-shezhi-aboutus";
        cell.cellName = @"关于我们";
    }else{
        if ([SYUserInformation sharedInstance].isLogin) {
            if (indexPath.row == 0) {
                cell.imageName = @"mjbtwo-qinghuancun";
                cell.cellName = @"清除缓存";
            }else{
                cell.imageName = @"kongkeexist";
                cell.cellName = @"退出登录";
            }
        }else{
            cell.imageName = @"kongkeclear";
            cell.cellName = @"清除缓存";
        }
        
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (![SYUserInformation sharedInstance].isLogin)
        {
            [self unLoginPostView];
            return;
        }
    }
    
    
    if (indexPath.section == 0) {//账户设置
        YDAAccountSettingController *vc = [[YDAAccountSettingController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else if (indexPath.section == 1){//关于我们
        YDAAboutUsController *vc = [[YDAAboutUsController alloc] init];
        vc.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:vc animated:YES];
        
    }else{
        if (indexPath.row == 0) {//清除缓存
            NSString *message = [NSString stringWithFormat:@"确认清除%@缓存？" , [self byteSize]];
            PZTipsAlertView *alert = [PZTipsViewManger shareDoubleTipsAlertViewTitle:@"提示" Mesage:message CancleTitle:@"取消" SureTitle:@"确定" CancleBlock:^{
                [self.pz_popupController dismiss];
                
            } SureBlock:^{
                
                [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
                    
                }];
                [self.pz_popupController dismiss];
                
            }];
            
            self.pz_popupController = [[PZPopUpController alloc] init];
            [self.pz_popupController dropAnimatedWithRotateAngle:30];
            [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
            
            
        }else{//退出登录
            [self postExistView];
        }
    }
    
}

//退出登录提示框
-(void)postExistView
{
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"确认退出登录?" ButtonTitle:@"确定" ButtonClickBlock:^{
        
        
        [self logoutRequest];
        
        [self.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    self.pz_popupController.layoutType = PZPopupLayoutTypeCenter;
    self.pz_popupController.slideStyle = PZPopupSlideStyleFade;
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
    
}


-(void)logoutRequest
{
    
    [[SYProgressHUD sharedInstance] showMBHudOnlyLoading];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer=[AFJSONRequestSerializer serializer];//声明请求的参数类型为json类型
    
    [manager.requestSerializer setValue:[[SYUserDataManger sharedInstance] getUserToken] forHTTPHeaderField:@"Authorization"];
    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:@"I" forHTTPHeaderField:@"endType"];
    
    //网络请求超时的时间
    manager.requestSerializer.timeoutInterval = 30;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes=[NSSet setWithObjects: @"text/html",@"text/json", @"application/json", @"text/javascript" ,@"text/plain",nil];
    ((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues = YES;
    
    
    NSString *url = [baseUrlHttp stringByAppendingString:@"/logout"];
    
    [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"退出登录失败" isExistNav:NO];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        [[SYProgressHUD sharedInstance] dismissMBWithTime:0];
        if (error.code == NSURLErrorBadServerResponse && [error.userInfo[@"NSLocalizedDescription"] isEqualToString:@"Request failed: forbidden (403)"]) {
            //注销成功
            [[SYUserDataManger sharedInstance] deleteUserDataTable];
            
            [SYUserInformation sharedInstance].isLogin = NO;
            [self.topView removeFromSuperview];
            self.topView = nil;
            [self unLoginView];
            [self.tableView reloadData];
            
        }
        else
        {
            [[NavTipsView defaultTipsView] showTipsBannerInView:self.view WithType:NavTipsViewTypeMessage text:@"退出登录失败" isExistNav:NO];
        }
        
    }];
    
}



-(NSString *)byteSize
{
    NSInteger byteSize = [[SDImageCache sharedImageCache] getSize];
    
    if (byteSize/1024 > 1024) {
        float MbSize = byteSize/1024/1024;
        return [NSString stringWithFormat:@"%.1fM",MbSize];
    }else
    {
        float MbSize = byteSize/1024;
        return [NSString stringWithFormat:@"%.1fK",MbSize];
    }
}
//未登录提示
-(void)unLoginPostView
{
    LK(weakSelf)
    //没有登录 弹出登录提示
    PZTipsAlertView *alert = [PZTipsViewManger shareSingleTipsAlertViewTitle:@"提示" Mesage:@"请先登录操作" ButtonTitle:@"我知道了" ButtonClickBlock:^{
        [weakSelf.pz_popupController dismiss];
    }];
    self.pz_popupController = [[PZPopUpController alloc] init];
    [self.pz_popupController dropAnimatedWithRotateAngle:30];
    self.pz_popupController.layoutType = PZPopupLayoutTypeCenter;
    self.pz_popupController.slideStyle = PZPopupSlideStyleFade;
    [self.pz_popupController presentContentView:alert duration:0.75 springAnimated:YES];
}

@end
